<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { delayApi } from '@/apis/task.js';
// 1. 延迟提货表单数据
const formData = ref({
	delayReason: '',
	delayTime: '',
	id: ''
});
//  原计划提货时间
const planTime = ref('');
const planTimes = ref('');
onLoad((params) => {
	console.log('参数：', params);
	formData.value.id = params.id;
	planTime.value = params.planDepartureTime;
	planTimes.value = params.planDepartureTime;
});

//选中的时间
const selcheange = (e) => {
	console.log('选中时间', e.detail.value);
	planTime.value = planTime.value.split(' ')[0];
	console.log('原始时间', planTime.value);
	formData.value.delayTime = `${planTime.value} ${e.detail.value}`;
};
//统计输入的字数
const total = computed(() => formData.value.delayReason.length);

//时间校验    // 选中时间 不能小于原始时间 并且 不大于 2小时
const isDelayTimeOk = computed(() => {
	const start = +new Date(planTimes.value); //原始时间
	const end = +new Date(formData.value.delayTime); //选中时间
	return end - start > 0 && end - start <= 7200 * 1000;
});
//延迟原因校验
const isDelayReasonOk = computed(() => {
	return formData.value.delayReason.length <= 50 && formData.value.delayReason.length > 0;
});
//兜底校验 禁用按钮
const isSubmitDisable = computed(() => {
	return !isDelayTimeOk.value || !isDelayReasonOk.value;
});
// 延迟提交
const submit = async () => {
	console.log('校验通过');
	await delayApi(formData.value);
	setTimeout(function () {
		uni.showToast({ title: '延迟成功...' });
	}, 1000);
	uni.reLaunch({
		url: '/pages/task/index'
	});
};
</script>

<template>
	<view class="page-container">
		<uni-list :border="false">
			<uni-list-item title="原定时间 " showArrow :rightText="planTimes" />
			<uni-list-item title="延迟时间" showArrow>
				<template v-slot:footer>
					<picker @change="selcheange" class="time-picker" mode="time" :value="planTime">
						<text v-if="!formData.delayTime">不可超过2个小时</text>
						<text :class="{ error: isDelayTimeOk === false }" v-else>{{ formData.delayTime + ':00' }}</text>
					</picker>
				</template>
			</uni-list-item>
			<uni-list-item direction="column">
				<template v-slot:body>
					<view class="textarea-wrapper">
						<textarea v-model="formData.delayReason" class="textarea" placeholder-style="color: #818181" placeholder="请输入延迟提货原因"></textarea>
						<text class="words-count">{{ total }}/50</text>
					</view>
				</template>
			</uni-list-item>
			<uni-list-item :border="false">
				<template v-slot:body>
					<button :disabled="isSubmitDisable" @click="submit" class="button">提交</button>
				</template>
			</uni-list-item>
		</uni-list>
	</view>
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
